//
//  ASIHTTPConnection.m
//  Growth_iPhone
//
//  Created by Steven on 8/8/12.
//  Copyright (c) 2012 MEET Studio. All rights reserved.
//


#import "ASIHTTPConnection.h"
#import "HB+ASIHTTPRequest.h"

#import "CJSONDeserializer.h"

@interface ASIHTTPConnection (Private)
- (NSDictionary *)parseJSON:(NSData *)data isDict:(BOOL)isDict;
@end

@implementation ASIHTTPConnection

@synthesize connectionDelegate;
@synthesize request;
@synthesize isResultDict;

- (void)dealloc
{
    CLog(@"ASIHTTPConnection dealloc!");
    
    connectionDelegate = nil;
    
    [request clearDelegatesAndCancel];
    [request release];
    
    [super dealloc];
    
    CLog(@"ASIHTTPConnection dealloc End!");
}

- (id)initGETWithURL:(NSURL *)newURL
{
    return [self initGETWithURL:newURL resultDict:YES];
}

- (id)initGETWithURL:(NSURL *)newURL resultDict:(BOOL)resultDict
{
    if (self = [super init]) {
        self.isResultDict = resultDict;
        
        request = [ASIHTTPRequest requestWithURL:newURL isHeader:YES];
        [request setDelegate:self];
        //[request setDownloadProgressDelegate:self];
        
    }
    return self;
}

- (id)initGETWithURL:(NSURL *)newURL resultDict:(BOOL)resultDict isCache:(BOOL)isCache
{
    
    if (self = [super init]) {
        self.isResultDict = resultDict;
        
        request = [ASIHTTPRequest requestWithURL:newURL isHeader:YES];
        [request setDelegate:self];
        
        if (isCache) {
            
            [request setCachePolicy:ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy];
            
            [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
            
            [request setDownloadCache:[ASIDownloadCache sharedCache]];
            
        }
        
    }
    return self;
    
}

- (id)initPOSTWithURL:(NSURL *)newURL jsonData:(NSData *)jsonData
{
    return [self initPOSTWithURL:newURL jsonData:jsonData resultDict:YES];
}


- (id)initPOSTWithURL:(NSURL *)newURL jsonData:(NSData *)jsonData resultDict:(BOOL)resultDict
{
    if (self = [super init]) {
        self.isResultDict = resultDict;
        
        request = [ASIHTTPRequest requestWithURL:newURL isHeader:YES];
        [request setDelegate:self];
        //[request setUploadProgressDelegate:self];
        
        NSMutableData *httpData = [NSMutableData data];
        [httpData appendData:jsonData];
        
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        [request setPostBody:httpData];
        // Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
        [request setRequestMethod:@"POST"];
    }
    return self;
}


//开启请求
- (BOOL)start
{
    if (request) {
        [request start];
        return YES;
    }
    else {
        return NO;
    }
}

- (BOOL)startAsynchronous
{
    if (request) {
        [request startAsynchronous];
        return YES;
    }
    else {
        return NO;
    }
}

- (BOOL)startSynchronous
{
    if (request) {
        [request startSynchronous];
        return YES;
    }
    else {
        return NO;
    }
}

#pragma mark - UploadProgressDelegate


- (void)request:(ASIHTTPRequest *)requestTemp didReceiveBytes:(long long)bytes
{
    NSString *response = [requestTemp responseString];
    CLog(@"\nRequest receive response %@", response);
    
    CLog(@"\ndidReceiveBytes %lld", bytes);
}

- (void)request:(ASIHTTPRequest *)requestTemp didSendBytes:(long long)bytes
{
    NSString *response = [requestTemp responseString];
    CLog(@"\nRequest send response %@", response);
    
    CLog(@"\ndidSendBytes %lld", bytes);
}


#pragma mark - Request delegate

- (void)requestStarted:(ASIHTTPRequest *)requestTemp
{
    NSInteger statusCode = [requestTemp responseStatusCode];
    CLog(@"Request Started statuscode %d", statusCode);
}

- (void)requestFinished:(ASIHTTPRequest *)requestTemp
{
    NSURL *url = [requestTemp url];

    NSInteger statusCode = [requestTemp responseStatusCode];
    
    @try {
        
        CLog(@"Request Finished statuscode %d", statusCode);
        
        [LoadingView hideWithAnimated:YES];
        
        if (statusCode == 200) {
            
            //Delegate 方法验证
            if (connectionDelegate && [connectionDelegate respondsToSelector:@selector(requestFinished:resultDict:URL:info:)]) {
                
                NSData *data = [requestTemp responseData];
                
                
                NSDictionary *infoDict = [requestTemp userInfo];
                
                NSDictionary *dict = [self parseJSON:data isDict:isResultDict];
                [connectionDelegate requestFinished:self resultDict:dict URL:url info:infoDict];
                
                CLog(@"Dict:%@", dict);
            }
        }
        else {
            NSError *error = [NSError errorWithDomain:@"数据获取错误！" code:statusCode userInfo:nil];
            
            CLog(@"Request Finished Error with status code %d", statusCode);
            
            //Delegate 方法验证
            if (connectionDelegate && [connectionDelegate respondsToSelector:@selector(requestFailed:error:URL:info:)]) {
                
                NSURL *url = [requestTemp url];
                NSDictionary *infoDict = [requestTemp userInfo];
                
                NSData *data = [[ASIDownloadCache sharedCache] cachedResponseDataForURL: url];
                
                if (data != nil) { //有缓存
                    
                    NSDictionary *dict = [self parseJSON:data isDict:isResultDict];
                    CLog(@"statuCode404 cache dict %@", dict);
                    [connectionDelegate requestFinished:self resultDict:dict URL:url info:infoDict];
                    
                }
                else{
                    
                    // NSDictionary *infoDictWithStatuCode = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:statusCode] forKey:@"statusCode"];
                    
                    [connectionDelegate requestFailed:self error:error URL:url info:infoDict];
                    
                }
                
            }
        }
        
        
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
    
}

- (void)requestFailed:(ASIHTTPRequest *)requestTemp
{
    [LoadingView hideWithAnimated:YES];
    
    NSURL *url = [requestTemp url];
    CLog(@"Request Failed URL:%@", url);
    NSInteger statusCode = [requestTemp responseStatusCode];
    CLog(@"Request Failed statuscode %d", statusCode);
    NSError *error = [requestTemp error];
    CLog(@"Request Failed error %@", error);
    
    //Delegate 方法验证
    if (connectionDelegate && [connectionDelegate respondsToSelector:@selector(requestFailed:error:URL:info:)]) {
        NSURL *url = [requestTemp url];
        NSDictionary *infoDict = [requestTemp userInfo];
        [connectionDelegate requestFailed:self error:error URL:url info:infoDict];
    }
}

#pragma mark - JSON
- (NSDictionary *)parseJSON:(NSData *)data isDict:(BOOL)isDict{
	CLog(@"Parsing JSON  isDict %d", isDict);

    //对array数据添加object外壳，统一转为dict
    if (!isDict) {
        NSError *error = nil;
        NSString *string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSString *str=[NSString stringWithFormat:@"{\"object\":%@}",string];
        
        NSData *dat=[str dataUsingEncoding: NSUTF8StringEncoding];
        NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:dat error:&error];
        
        return dictionary;
    }
    else {
        NSError *error = nil;
        
        NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
        
        return dictionary;
    }
}

@end
